<template>
  <div class="singer">
    <list-view @select="selectSinger" :singers="singers"></list-view>
		<router-view></router-view>
  </div>
</template>

<script>
import ListView from 'base/listview/listview'
import {getSingerList} from 'api/singer'
import {ERR_OK} from 'api/config'
import Singer from 'common/js/singer'
import {mapMutations} from 'vuex'
const HOT_SINGER_LEN = 10
const HOT_NAME = '热门'
export default {
  data() {
    return {
      singers: []
    }
  },
  components: {
    ListView
  },
  created() {
    this._getSingerList()
  },
  mounted() {

  },
  methods: {
		selectSinger(singer){
			// console.log(singer)
			this.$router.push({path:`/singer/${singer.id}`})
			this.setSinger(singer) //执行了mutatiosn.js里的函数赋值给state.singer,在singer-detail.vue通过...mapGetters获取
		},
    _getSingerList() {
      getSingerList().then(res => {
        if (res.code === ERR_OK) {
          this.singers = this._normalizeSinger(res.data.list)
        }
      })
    },
    _normalizeSinger(list) {
      let map = {
        hot: {
          title: HOT_NAME,
          items: []
        }
      }
      list.forEach((item, index) => {
        if (index < HOT_SINGER_LEN) {
          map.hot.items.push(new Singer({
            name: item.Fsinger_name,
            id: item.Fsinger_mid
          }))
        }
        const key = item.Findex
        if (!map[key]) {
          map[key] = {
            title: key,
            items: []
          }
        }
        map[key].items.push(new Singer({
          id: item.Fsinger_mid,
          name: item.Fsinger_name
        }))
      })
      // 对map进行排序
      let hot = []
      let ret = []
      for (let key in map) {
        let val = map[key]
        if (val.title.match(/[a-zA-Z]/)) {
          ret.push(val)
        } else if (val.title === HOT_NAME) {
          hot.push(val)
        }
      }
      ret.sort((a, b) => {
        // charCodeAt 返回指定位置字符的unicode编码A=65 B=66
        return a.title.charCodeAt(0) - b.title.charCodeAt(0)// 返回结果为true,为顺序排列
      })
      return hot.concat(ret)
    },
		...mapMutations({
			setSinger:'SET_SINGER'
		})
	}
}
</script>

<style scoped lang='stylus'>
.singer
  position: fixed
  top: 88px
  bottom: 0
  width: 100%
</style>